package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.exception.RRException;
import com.atguigu.common.to.SkuHasStockTo;
import com.atguigu.common.to.SkuReductionTo;
import com.atguigu.common.to.SpuBoundsTo;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.entity.vo.*;
import com.atguigu.gulimall.product.feign.CouponFeignService;
import com.atguigu.gulimall.product.feign.SearchFeignService;
import com.atguigu.gulimall.product.feign.WareFeignService;
import com.atguigu.gulimall.product.service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("spuInfoService")
@Slf4j
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Resource
    SpuInfoDao spuInfoDao;
    @Autowired
    SpuInfoDescService spuInfoDescService;
    @Autowired
    SpuImagesServiceImpl spuImagesService;
    @Autowired
    ProductAttrValueService productAttrValueService;
    @Autowired
    AttrService attrService;
    @Autowired
    SkuInfoService skuInfoService;
    @Autowired
    SkuImagesService skuImagesService;
    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    CouponFeignService couponFeignService;
    @Autowired
    BrandService brandService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    WareFeignService wareFeignService;
    @Autowired
    SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public boolean saveSpuBaseInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
        return true;
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        LambdaQueryWrapper<SpuInfoEntity> queryWrapper = new LambdaQueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and((wrapper) -> {
                wrapper.eq(SpuInfoEntity::getId, key)
                        .or().like(SpuInfoEntity::getSpuName, key)
                        .or().like(SpuInfoEntity::getSpuDescription, key);
            });
        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            queryWrapper.eq(SpuInfoEntity::getPublishStatus, status);
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equals(brandId)) {
            queryWrapper.eq(SpuInfoEntity::getBrandId, brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equals(catelogId)) {
            queryWrapper.eq(SpuInfoEntity::getCatalogId, catelogId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params), queryWrapper);
        return new PageUtils(page);
    }

    @Override
    @Transactional
    public boolean up(Long spuId) {
        /** 1、查出当前spuId对应的所有sku信息 */
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.getSkusBySpuId(spuId);

        /** 4、查询当前sku的可以被用来检索的所有规格属性 */
        //查询spu的所有规格参数
        List<ProductAttrValueEntity> baseAttrs = productAttrValueService.baseAttrlistBySpuId(spuId);
        //映射出这些规格参数的id
        List<Long> attrIds = baseAttrs.stream().map(baseAttr -> {
            return baseAttr.getAttrId();
        }).collect(Collectors.toList());
        //从这些规格参数中，挑出可以被检索的
        List<Long> listAttrIds = attrService.getSearchAttrs(attrIds);
        Set<Long> setAttrIds = new HashSet<>(listAttrIds);  //set的contains效率更高，为O(1)复杂度，而list的为 O(n)
        //将这些可以被检索的规格参数对象过滤出来
        List<SkuEsModel.Attrs> attrsList = baseAttrs.stream().filter(item -> {
            return setAttrIds.contains(item.getAttrId());
        }).map(baseAttr -> {
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(baseAttr, attrs);
            return attrs;
        }).collect(Collectors.toList());

        /** 3、发送远程调用，库存系统查询是否有库存 */
        Map<Long, Boolean> stockMap = null;
        try {
            List<Long> skuIdList = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
            R r = wareFeignService.getSkusHasStock(skuIdList);
            TypeReference<List<SkuHasStockTo>> typeReference = new TypeReference<List<SkuHasStockTo>>() {};
            List<SkuHasStockTo> data = r.getData(typeReference);
            stockMap = data.stream()
                    .collect(Collectors.toMap(SkuHasStockTo::getSkuId, SkuHasStockTo::isHasStock));
        } catch (Exception e) {
            log.info("库存异常原因：{}", e);
            throw new RRException("库存服务查询异常");
        }

        /** 2、封装每个sku的信息 */
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> upProducts = skuInfoEntities.stream().map(skuInfoEntity -> {
            //组装需要的数据
            SkuEsModel esModel = new SkuEsModel();
            BeanUtils.copyProperties(skuInfoEntity, esModel);
            esModel.setSkuPrice(skuInfoEntity.getPrice());
            esModel.setSkuImg(skuInfoEntity.getSkuDefaultImg());

            if(finalStockMap != null){
                esModel.setHasStock(finalStockMap.get(skuInfoEntity.getSkuId()));
            } else {
                esModel.setHasStock(false);
            }

            //TODO 热度评分
            esModel.setHotScore(0L);

            //查询品牌名称和品牌图片
            BrandEntity brandEntity = brandService.getById(esModel.getBrandId());
            esModel.setBrandName(brandEntity.getName());
            esModel.setBrandImg(brandEntity.getLogo());

            //查询类别名称
            CategoryEntity categoryEntity = categoryService.getById(esModel.getCatalogId());
            esModel.setCatalogName(categoryEntity.getName());

            //设置检索属性（规格参数，由于每个sku的规格参数都由其spu决定，因此attrsList在外面获取）
            esModel.setAttrs(attrsList);
            return esModel;
        }).collect(Collectors.toList());

        /** 5、将数据发送给es进行保存；gulimall-search */
        R r = searchFeignService.productStatusUp(upProducts);
        if(r.getCode() == 0){
            //远程调用成功
            //修改当前spu状态为已上架
            spuInfoDao.updateSpuStatus(spuId, ProductConstant.StatusEnum.UP_SPU.getCode());
        } else {
            //远程调用失败
            //TODO 重复调用的问题？（接口幂等性；重试机制？）
        }
        return true;
    }

    /**
     * TODO 保存失败部分高级部分再讲
     *
     * @author 胡菜鸡
     * @date 2021/12/27 16:41
     */
    @Override
    @Transactional
    public boolean saveSpuInfo(SpuSaveVo spuSaveVo) {
        /** 1、保存spu基本信息 */
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveSpuBaseInfo(spuInfoEntity);

        /** 2、保存spu的描述信息 */
        List<String> decript = spuSaveVo.getDecript();  //获取所有的描述信息
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        //将list中的数据用逗号拼接成字符串
        spuInfoDescEntity.setDecript(String.join(",", decript));
        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);

        /** 3、保存spu的图片集 */
        List<String> images = spuSaveVo.getImages();    //获取所有的图片路径
        spuImagesService.saveSpuImages(spuInfoEntity.getId(), images);

        /** 4、保存spu的规格参数 */
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();   //获取所有的规格参数
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map((baseAttr) -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            valueEntity.setAttrId(baseAttr.getAttrId());
            //根据属性Id查询属性对象 -> 获取到属性名称
            AttrEntity attrEntity = attrService.getById(baseAttr.getAttrId());
            valueEntity.setSpuId(spuInfoEntity.getId());        //设置参数所属商品ID
            valueEntity.setAttrName(attrEntity.getAttrName());  //设置属性名称
            valueEntity.setAttrValue(baseAttr.getAttrValues());
            valueEntity.setQuickShow(baseAttr.getShowDesc());
            valueEntity.setAttrSort(0);
            return valueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveSpuProductAttr(collect);


        /** 5、保存spu的积分信息（远程调用） */
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        BeanUtils.copyProperties(spuSaveVo.getBounds(), spuBoundsTo);
        spuBoundsTo.setSpuId(spuInfoEntity.getId());
        couponFeignService.saveSpuBounds(spuBoundsTo);


        /** 6、保存当前spu对应的所有sku信息 */
        List<Skus> skus = spuSaveVo.getSkus();
        if (skus != null && skus.size() > 0) {
            skus.forEach(sku -> {
                // 6.1 保存sku的基本信息
                String defaultImg = "";
                for (Images image : sku.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();
                        break;
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);

                skuInfoService.saveSkuInfo(skuInfoEntity);

                // 6.2 sku的图片信息
                List<SkuImagesEntity> skuImagesEntities = sku.getImages().stream().filter((entity) -> {
                    //过滤出拥有图片路径的对象
                    return !StringUtils.isEmpty(entity.getImgUrl());
                }).map((image) -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                    skuImagesEntity.setImgUrl(image.getImgUrl());
                    skuImagesEntity.setDefaultImg(image.getDefaultImg());
                    skuImagesEntity.setImgSort(0);
                    return skuImagesEntity;
                }).collect(Collectors.toList());
                skuImagesService.saveSkuImageInfo(skuImagesEntities);

                // 6.3 sku的销售/属性信息
                List<Attr> skuAttrs = sku.getAttr();
                List<SkuSaleAttrValueEntity> skuAttrEntities = skuAttrs.stream().map((skuAttr) -> {
                    SkuSaleAttrValueEntity skuAttrEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(skuAttr, skuAttrEntity);
                    skuAttrEntity.setSkuId(skuInfoEntity.getSkuId());
                    skuAttrEntity.setAttrSort(0);
                    return skuAttrEntity;
                }).collect(Collectors.toList());

                skuSaleAttrValueService.saveSkuAttrInfo(skuAttrEntities);

                // 6.4 sku的优惠信息（远程调用）
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(sku, skuReductionTo);
                skuReductionTo.setSkuId(skuInfoEntity.getSkuId());
                couponFeignService.saveSkuReduction(skuReductionTo);


            });
        }


        return true;
    }

}